<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { useUseStore } from "@/stores/user";
import { getRecordApi, getLastAgreementApi, addProtocolApi, modifyProtocolStatusAPI } from "@/server/api/futurePi"
import { onBeforeMount } from "vue";
import { showLoadingToast, showSuccessToast, showFailToast } from 'vant';
import { useI18n } from "vue-i18n";

const { t } = useI18n();
//获取翻译
const label = t('FlowerFuture.ContactInformation')
const placeholder = t('FlowerFuture.YourTelephoneOrEmail')

const router = useRouter();
//展示合同
const showProtocol = ref(false);
//有效消费总额
const total = ref(null);
//合同状态
const protocalStatus = ref(null);
// 开通合同所需参数
const info = ref({
  uid: useUseStore().userId,
  exchangeRate: null,//协议的兑换
  realName: useUseStore().userId,
  email: null,
  phone: null
});
//加载事件 1分钟
const loadTime = ref(60000);
//获取的最后一条的协议的协议号，如果是 协议状态是 生效中（0） 则此协议号可以用以终止协议
const protocalId = ref(null);

//获得有效消费总额
const getRecord = async () => {

  const res = await getRecordApi(useUseStore().userId);
  if (res.data.code == 200) {
    total.value = res.data.data;
  }
};

//判断状态
const judgeStatus = () => {
  console.log(protocalStatus, "协议状态");
  if (protocalStatus.value == null) {
    return true;
  } else if (protocalStatus.value == 0) {
    return false;
  } else if (protocalStatus.value == 1 || protocalStatus.value == 2) {
    return true;
  }
};

//获取最后一条协议 用于协议页面的信息展示
const getLastAgreement = async () => {
  const res = await getLastAgreementApi(useUseStore().userId);
  if (res.data.code == 200) {
    showProtocol.value = true;
    // console.log(res.data.data, "-----");
    protocalStatus.value = res.data.data.status;
    protocalId.value = res.data.data.protocolId;
    for (let key in res.data.data) {
      //如果返回的数据里面的属性不为空
      if (res.data.data[key] != null && res.data.data[key] != "" && key in info.value) {
        info.value[key] = res.data.data[key];
      }
    }
  }
};

//添加一条协议
const addProtocol = async () => {
  //判断值是否填了，email和电话只能任一为空
  const temp = [];
  for (let key in info.value) {
    if (!info.value[key]) {
      console.log(key, "没有值的key");
      if (key == "email" || key == "phone") {
        temp.push(key);
        console.log(key, "电话或邮件");
      } else {
        console.log(key, "其它");
        showFailToast('');
        return false;
      }
      if (temp.length > 1) {
        showFailToast('');
        return false;
      }
    }
  };
  // 等待动画
  showLoadingToast({
    message: '',
    forbidClick: true,
    loadingType: 'spinner',
    duration: loadTime.value
  });
  const res = await addProtocolApi(info.value);
  console.log(res, "添加协议");
  if (res.data.code == 200) {
    loadTime.value = 0;
    showSuccessToast('');
    router.go(0);
  }
}

//终止协议
const Termination = async () => {
  const info = {
    protocolId: protocalId.value,
    status: 1
  }
  const res = await modifyProtocolStatusAPI(info);
  //等待动画
  showLoadingToast({
    message: '',
    forbidClick: true,
    loadingType: 'spinner',
    duration: 2000
  })
  console.log(res);
  if (res.data.code == 200) {
    router.go(0);
  } else {
    showFailToast('');
  }

}

onBeforeMount(() => {
  //获得最后一条协议
  getLastAgreement();
  showLoadingToast({
    message: '',
    forbidClick: true,
    loadingType: 'spinner',
    duration: 2500
  })
});
onMounted(() => {
  //获取消费总额
  getRecord();
})
</script>

<template>
  <div class="future" v-show="showProtocol">
    <div class="top">
      <div class="topleft">
        <van-icon name="arrow-left" style="font-size: 25px" @click="router.back()" />
      </div>
      <div class="title">{{ $t("FlowerFuture.title") }}</div>
      <div class="toptight"></div>
    </div>
    <p class="p1" v-show="protocalStatus == null">{{ $t("FlowerFuture.neverAgree") }}</p>
    <p class="p1" v-if="judgeStatus()">{{ $t("FlowerFuture.overAndCover") }}</p>
    <p class="p1" v-if="!judgeStatus()">{{ $t("FlowerFuture.work") }}</p>
    <!-- 消费总积分 -->
    <div class="amount">{{ $t("FlowerFuture.leiji") }}:{{ total }}</div>
    <!-- 规则 -->
    <div class="rule">
      <div class="title">{{ $t("FlowerFuture.smalltitle") }}</div>

      <div class="firstparty">
        <!-- 甲方 -->
        <div>{{ $t("FlowerFuture.jiafang") }}:{{ info.uid }}</div>

        <!-- <van-cell-group inset>
          <van-field v-model="info.realName" label="姓名" placeholder="[您的名字]" />
        </van-cell-group> -->

        <van-cell-group inset>
          <van-field v-model="info.phone" :label="$t('FlowerFuture.ContactInformation')"
            :placeholder="$t('FlowerFuture.phone')" />
        </van-cell-group>

        <van-cell-group inset>
          <van-field v-model="info.email" :label="$t('FlowerFuture.email')"
            :placeholder="$t('FlowerFuture.emailTip')" />
        </van-cell-group>

      </div>

      <div class="header">{{ $t("FlowerFuture.yifang") }}：[PiPayShop]</div>
      <div class="header">{{ $t("FlowerFuture.GivenThat") }}：</div>
      <div>1.{{ $t("FlowerFuture.GivenThatContent.One") }}</div>
      <div>2. {{ $t("FlowerFuture.GivenThatContent.Two") }}</div>
      <div>
        {{ $t("FlowerFuture.GivenThatResult") }}：
      </div>
      <div class="header">{{ $t("FlowerFuture.FirstProtocolTitle") }}</div>
      <div>1. {{ $t("FlowerFuture.content1.One") }}</div>
      <div>
        2. {{ $t("FlowerFuture.content1.Two") }}
      </div>
      <div>
        3.
        {{ $t("FlowerFuture.content1.Three") }}
      </div>
      <div>
        4. {{ $t("FlowerFuture.content1.Four") }}
      </div>
      <div>
        5. {{ $t("FlowerFuture.content1.Five") }}
      </div>
      <div class="header">{{ $t("FlowerFuture.SecondExchangeMethod") }}</div>
      <div>
        1.{{ $t("FlowerFuture.content2.One") }}
      </div>
      <div>2. {{ $t("FlowerFuture.content2.Two") }}</div>
      <div class="header">{{ $t("FlowerFuture.ThirdEffectivenessOfTheAgreement") }}</div>
      <div>
        {{ $t("FlowerFuture.content3") }}
      </div>
      <div class="header">**{{ $t("FlowerFuture.FourDisputeResolution") }}</div>
      <div>{{ $t("FlowerFuture.Content4") }}</div>
    </div>
    <div class="points">
      <div class="title">{{ $t("FlowerFuture.InputTitle") }}</div>

      <van-cell-group inset>
        <van-field v-model="info.exchangeRate" label="ecny" placeholder="1pi=ecny" />
      </van-cell-group>
      <div class="scale">{{ info.exchangeRate }}eCNY=1pi</div>
    </div>
    <div class="btn" v-if="judgeStatus()" @click="addProtocol">{{ $t("FlowerFuture.agreeProtocol") }}</div>
    <div class="btn" v-if="!judgeStatus()" @click="Termination">{{ $t("FlowerFuture.termination") }}</div>


  </div>
</template>
<style lang="scss" scoped>
.future {
  width: 100vw;
  padding: 0 20px;
  box-sizing: border-box;

  .top {
    padding: 20px 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .topleft {
      width: 20px;
    }

    .title {
      font-size: 20px;
    }

    .toptight {
      width: 20px;
    }
  }

  .amount {
    font-size: 18px;
  }

  .rule {
    font-size: 16px;

    .title {
      text-align: center;
      font-size: 20px;
      margin: 10px;
    }

    .header {
      font-size: 18px;
      font-weight: 700;
      margin: 5px 0;
    }

    .firstparty {
      font-size: 18px;
      font-weight: 700;
      margin: 10px 0;
    }
  }

  .points {
    margin: 10px 0;
    padding: 5px;
    border-radius: 10px;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
    /* 水平偏移量 | 垂直偏移量 | 模糊半径 | 颜色 */
    font-size: 20px;

    .scale {
      text-align: center;
      padding: 0 30px;
    }

    .title {
      font-size: 16px;
      flex-wrap: 700;
    }
  }

  .btn {
    margin: 0 auto;
    font-size: 16px;
    color: white;
    // width: 120px;
    height: 40px;
    background-color: #642e8e;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 15px;
  }

  .p1 {
    font-size: 12px;
    color: red;
  }
}
</style>